<?php
/**
 * Created by PhpStorm.
 * User: mr.lee
 * Date: 2018/10/17
 * Time: 11:54 AM
 */

namespace Bank;
class HuifuServer
{


//商户信息变更接口	http://pttest.chinapnr.com/nsposmweb /webB1420	https://nspos.chinapnr.com/nsposmweb /webB1420
//银联JS支付	https://amtqrcp.testpnr.com/qrcp/E1112	https://nspos.cloudpnr.com/qrcp/E1112
//小程序支付	https://amtqrcp.testpnr.com/qrcp/E1113	https://nspos.cloudpnr.com/qrcp/E1113
    const MCH_JOIN = "https://nspos.chinapnr.com/nsposmweb/webB1412";//商户入驻
    const UPLOAD_IMG = "https://nsposf.cloudpnr.com/nsposfweb/webB9002/uploadWebMerPic";//商户图片上传接口
    const QRCODE_PAY = "https://nspos.cloudpnr.com/qrcp/E1103";//正扫接口
    const B2C_PAY = "https://nspos.cloudpnr.com/qrcp/E1102";//被扫接口
    const C2B_PAY = "https://nspos.cloudpnr.com/qrcp/E1101";//台牌支付接口
    const Order_Reverse = "https://nspos.cloudpnr.com/qrcp/E1105";//二维码撤销接口
    const Order_Refund = "https://nspos.cloudpnr.com/qrcp/E1106";//二维码退货接口
    const Order_Query = "https://nspos.cloudpnr.com/qrcp/P3009";//二维码订单查询接口
    const Delay_Order = "https://nspos.chinapnr.com/nsposr/B7108";//延迟入账确认收货接
    const Final_State = "https://dst.chinapnr.com/dst/getFinalState";//交易终态获取接口
    const Change_Act = "https://nspos.chinapnr.com/nsposmweb/webB1419/changeAct";//结算信息修改
    const Wx_Config = "https://nspos.chinapnr.com/nsposmweb/webB1418/wxConfig";//微信公众号配置
    const Wx_Config_Query = "https://nspos.chinapnr.com/nsposmweb/webB1418/queryWxConfig";//微信公众号配置查询
    const Mch_Balance = "https://nspos.chinapnr.com/nsposmweb/webB7002";//商户余额获取接口
    const Mch_T0 = "https://nspos.chinapnr.com/nsposmweb/webB7001";//商户t0取现
    const Mch_Updata = "https://nspos.chinapnr.com/nsposmweb/webB1420";//商户信息变更接口
    const UnionPay_Js_Pay = "https://nspos.cloudpnr.com/qrcp/E1112";//银联JS支付
    const MicroApp_Pay = "https://nspos.cloudpnr.com/qrcp/E1113";//小程序支付


    public function upload_img($data)
    {
        $url = self::UPLOAD_IMG;
        $re_param = $this->http_post($url, $data, true);
//        return $re_param;
        return json_decode($re_param, true);

    }

    public function mch_join($data)
    {
        $url = self::MCH_JOIN;
        $re_param = $this->http_post($url, $data, false);

        return json_decode($re_param, true);

    }

    public function mch_updata($data)
    {
        $url = self::Mch_Updata;
        $re_param = $this->http_post($url, $data, false);

        return json_decode($re_param, true);

    }
    public function change_act($data)
    {
        $url = self::Change_Act;
        $re_param = $this->http_post($url, $data, false);

        return json_decode($re_param, true);

    }
    public function wx_config($data)
    {

        $url = self::Wx_Config;
        $re_param = $this->http_post($url, $data, false);

        return json_decode($re_param, true);

    }
    public function order_query($data){
         $url = self::Order_Query;
        $re_param = $this->http_post($url, $data, false);

        return json_decode($re_param, true);
    }

    public function wx_config_query($data)
    {

        $url = self::Wx_Config_Query;
        $re_param = $this->http_post($url, $data, false);

        return json_decode($re_param, true);

    }

    public function qrcode_pay($data)
    {

        $url = self::QRCODE_PAY;
        $re_param = $this->http_post($url, $data, false);

        return json_decode($re_param, true);

    }
    public function c2b_pay($data)
    {

        $url = self::C2B_PAY;
        $re_param = $this->http_post($url, $data, false);

        return json_decode($re_param, true);

    }
    public function b2c_pay($data)
    {

        $url = self::B2C_PAY;
        $re_param = $this->http_post($url, $data, false);

        return json_decode($re_param, true);

    }
    public function http_post($url, $param, $post_file = false)
    {
        $oCurl = curl_init();
        if (stripos($url, "https://") !== FALSE) {
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
        }
        if (PHP_VERSION_ID >= 50500 && class_exists('\CURLFile')) {
            $is_curlFile = true;
        } else {
            $is_curlFile = false;
            if (defined('CURLOPT_SAFE_UPLOAD')) {
                curl_setopt($oCurl, CURLOPT_SAFE_UPLOAD, false);
            }
        }
        if (is_string($param)) {
            $strPOST = $param;
            curl_setopt($oCurl, CURLOPT_HTTPHEADER, array('Content-Type:application/json; charset=utf-8',

                'Content-Length: ' . strlen($param)));
        } elseif ($post_file) {

            if ($is_curlFile) {
                foreach ($param as $key => $val) {

                    if (substr($val, 0, 1) == '@') {

                        $param[$key] = new \CURLFile(realpath(substr($val, 1)));

                    }
                }

            }
            $strPOST = $param;
        } else {
            $aPOST = array();
            foreach ($param as $key => $val) {
                $aPOST[] = $key . "=" . urlencode($val);
            }
            $strPOST = join("&", $aPOST);
            curl_setopt($oCurl, CURLOPT_HTTPHEADER, array('Content-Type:application/x-www-form-urlencoded; charset=utf-8',));
        }

        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($oCurl, CURLOPT_POST, true);
        curl_setopt($oCurl, CURLOPT_POSTFIELDS, $strPOST);

        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);
        curl_close($oCurl);
//        return $aStatus["http_code"];
        if (intval($aStatus["http_code"]) == 200) {
            return $sContent;
        } else {
            return false;
        }
    }

    public function getParamsString($params)
    {
        if (!is_array($params))
            $params = array();
        ksort($params);
        $str = '';
        foreach ($params as $k => $v) {
            $str .= $v != '' ? $k . $v : '';
        }
        return $str;
    }

    /**
     * 根据原文生成签名内容
     *
     * @param string $data 原文内容
     *
     * @return string
     */
    public function createsign()
    {


    }

    public function sign($data)
    {
//        return $data;
        $filePath = '/data2/html/payos/extend/Bank/cert/cfca.pfx';
        if (!file_exists($filePath)) {
            return false;
        }
        $strLogCofigFilePath = "/data2/html/payos/extend/Bank/cfcalog.conf";
        $nResult = cfca_initialize($strLogCofigFilePath);
        $strSignAlg = "RSA";
        $strSignSourceData = $data;
        $strPfxFilePath = $filePath;
        $strPfxPassword = "huayi6142228";
        $strHashAlg = "SHA-256";
        // Msg PKCS7-attached Sign
        $strMsgPKCS7AttachedSignature = "";
        $nResult = cfca_signData_PKCS7Attached($strSignAlg, $strSignSourceData, $strPfxFilePath, $strPfxPassword, $strHashAlg, $strMsgPKCS7AttachedSignature);
        if (0 != $nResult) {
            return "\n cfca_signData_PKCS7Attached error:" . $nResult . "\n";
        }
        return $strMsgPKCS7AttachedSignature;
    }

    public function get_sign_data($data)
    {
        $private_key = '/data2/html/payos/extend/Bank/cert/cfca.pfx';
        if (!file_exists($private_key)) {
            return false;
        }
        $public_key = "/data2/html/payos/extend/Bank/cert/CFCA_ACS_OCA31.cer";
        $strSignAlg = "RSA";
        $strMsgPKCS7AttachedSignature = $data;
        $strPfxFilePath = $private_key;
        $strPfxPassword = "huayi6142228";
        $strHashAlg = "SHA-256";
        $strMsgP7AttachedSignCertContent = $public_key;
        $strLogCofigFilePath = "/data2/html/payos/extend/Bank/cfcalog.conf";
        cfca_initialize($strLogCofigFilePath);
        $strMsgP7AttachedSource = "";
        $nResult = cfca_verifyDataSignature_PKCS7Attached($strSignAlg, $strMsgPKCS7AttachedSignature, $strMsgP7AttachedSignCertContent, $strMsgP7AttachedSource);
        if (0 != $nResult) {
            return "\n cfca_signData_PKCS7Attached error:" . $nResult . "\n";
        }
        return $strMsgPKCS7AttachedSignature;
    }

    /**
     * 验证签名自己生成的是否正确
     *
     * @param string $data 签名的原文
     * @param string $signature 签名
     *
     * @return bool
     */
    public function verifySign($data, $signature)
    {
        $filePath = 'private.pfx';
        if (!file_exists($filePath)) {
            return false;
        }

        $pkcs12 = file_get_contents($filePath);
        if (openssl_pkcs12_read($pkcs12, $certs, '读取证书所需要的密码')) {
            $publicKey = $certs['cert'];
            $ok = openssl_verify($data, hex2bin($signature), $publicKey);
            if ($ok == 1) {
                return true;
            }
        }
        return false;
    }

    /**
     * 验证返回的签名是否正确
     * @filePath 为cer文件路径
     * @param string $data　要验证的签名原文
     * @param string $signature 签名内容
     *
     * @return bool
     */
    public function verifyRespondSign($data, $signature)
    {
        $filePath = 'public.cer';
        if (!file_exists($filePath)) {
            return false;
        }

        $cert = file_get_contents($filePath);
        $pubKeyId = openssl_get_publickey($cert);

        $signature = hex2bin($signature);
        $ok = openssl_verify(utf8_encode($data), $signature, $pubKeyId);

        if ($ok == 1) {
            openssl_free_key($pubKeyId);
            return true;
        }
        return false;
    }
    public function download_image($url, $fileName = '', $dirName, $fileType = array('jpg', 'gif', 'png'), $type = 1)
    {
        if ($url == '') {
            return false;
        }

        // 获取文件原文件名
        $defaultFileName = basename($url);

        // 获取文件类型
        $suffix = substr(strrchr($url, '.'), 1);
        if (!in_array($suffix, $fileType)) {
            return false;
        }

        // 设置保存后的文件名
        if(!$fileName){
            $fileName = $fileName == '' ? time() . rand(0, 9) . '.' . $suffix : $defaultFileName;
        }else{
            $fileName=$fileName.'.' . $suffix;
        }
        // 获取远程文件资源
        if ($type) {
            $ch = curl_init();
            $timeout = 30;
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
            $file = curl_exec($ch);
            curl_close($ch);
        } else {
            ob_start();
            readfile($url);
            $file = ob_get_contents();
            ob_end_clean();
        }

        // 设置文件保存路径
        //$dirName = $dirName . '/' . date('Y', time()) . '/' . date('m', time()) . '/' . date('d', time());
        $dirName = $dirName . '/' . date('Ym', time());
        if (!file_exists($dirName)) {
            mkdir($dirName, 0777, true);
        }

        // 保存文件
        $res = fopen($dirName . '/' . $fileName, 'a');
        fwrite($res, $file);
        fclose($res);

        return array(
            'fileName' => $fileName,
            'saveDir' => $dirName
        );
    }


}